package com.zlyx.easy.swagger.controller;

import java.util.Collection;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.zlyx.easy.core.tool.Ops;
import com.zlyx.easy.core.utils.RequestUtils;
import com.zlyx.easy.core.utils.RestUtils;
import com.zlyx.easy.swagger.config.ApiCache;
import com.zlyx.easy.swagger.config.ApiConfiguration;

import io.swagger.annotations.Api;

/**
 * @Auth 赵光
 * @Describle
 */
@Api(hidden = true)
@Controller
@RequestMapping("/easy-swagger")
public class SwaggerController {

	@Autowired
	private ApiConfiguration apiConfiguration;

	@ResponseBody
	@RequestMapping("/apis/get")
	public Map<String, Collection<String>> getGroupNames() {
		Map<String, Collection<String>> groupNames = null;
		if (Ops.isNotEmpty(apiConfiguration.getManagerUrl())
				&& Ops.nequals(apiConfiguration.getManagerUrl(), RequestUtils.getHost())) {
			groupNames = RestUtils.postForObject(apiConfiguration.getManagerUrl() + "easy-swagger/apis/get", null);
			if (groupNames == null && apiConfiguration.isAllowSinglen()) {
				groupNames = ApiCache.getApis();
			}
		} else {
			groupNames = ApiCache.getApis();
		}
		return groupNames;
	}

	@SuppressWarnings("unchecked")
	@ResponseBody
	@RequestMapping("/apis/register")
	public void registerApis(@RequestBody String body) {
		if (Ops.isNotEmpty(body)) {
			ApiCache.addApis(JSONObject.parseObject(body, Map.class));
		}
	}

	@GetMapping
	public String swagger() {
		return "redirect:docs.html";
	}
}
